package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.constants.admin.PublishArticleConstants;
import com.heima.model.common.constants.admin.WemediaConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsService wmNewsService;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenScan greenScan;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void autoScanWmNews(Integer id) {
        //1.校验参数 id
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "id不能为空");
        }
        //2.根据id查询数据
        WmNews wmNews = wmNewsService.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在");
        }
        //3.判断文章状态是否为1(必须是1)
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNews.getStatus())) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "文章状态不是待审核状态");
        }
        //4.抽取文章中所有文章内容和图片内容
        Map<String, Object> contentAndImages = handleTextAndImages(wmNews);
        //5.进行自动管理敏感词校验
        String content = (String) contentAndImages.get("content");
        boolean scanSensitive = handleSensitive(content, wmNews);
        if(!scanSensitive){
            // 返回false代表审核不成功   结束处理
            log.info("文章审核未通过，原因: 内容中包含敏感词");
            return;
        }
        //6.基于阿里云检测文本内容
        boolean scanText = handleTextScan(content,wmNews);
        if(!scanText){
            // 返回false代表审核不成功   结束处理
            log.info("文章审核未通过，原因: 内容中包含违规词汇");
            return;
        }
        //阿里云检测图片内容
        List<String> image = (List<String>) contentAndImages.get("images");
        boolean scanImages = handleImagesScan(image,wmNews);
        if(!scanImages){
            // 返回false代表审核不成功   结束处理
            log.info("文章审核未通过，原因: 图片中包含违规词汇");
            return;
        }
        //7全部通过状态改为8（通过审核）
        updateWmNews(WmNews.Status.SUCCESS.getCode(), "审核通过",wmNews);
        //TODO 通知定时发布文章
        //发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
    }

    /**
     * 阿里云检测图片内容
     * @param image 待检测的图片
     * @param wmNews    文章对象
     * @return
     */
    private boolean handleImagesScan(List<String> image, WmNews wmNews) {
        boolean flag = false;
        //调用greenScan返回结果
        try {
            ScanResult scanResult = greenScan.imageUrlScan(image);
            //判断结果中suggestion状态
            String suggestion = scanResult.getSuggestion();
            //pass(通过)、review(人工审核)、block(失败)   switch case
           switch (suggestion){
               case "block":
                   updateWmNews(WmNews.Status.FAIL.getCode(),"图片中包含违规信息："+scanResult.getLabel(),wmNews);
                   break;
               case "review":
                   updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "图片中有不确定因素，需要进一步人工审核:" ,wmNews);
                   break;
               case "pass":
                   flag=true;
                   break;
               default:
                   updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用状态异常，需要进一步人工审核:" ,wmNews);
                   break;
           }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "图片中有不确定因素，需要进一步人工审核:" ,wmNews);
        }
        return flag;
    }

    /**
     *阿里云检测文本内容
     * @param content   待审核的文本
     * @param wmNews    文章对象
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag =false;
        //调用greenScan返回结果
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            //判断结果中suggestion状态
            String suggestion = scanResult.getSuggestion();
            //pass(通过)、review(人工审核)、block(失败)    switch case
            switch (suggestion){
                case "block":
                    updateWmNews(WmNews.Status.FAIL.getCode(),"文章中包含违规词汇："+scanResult.getLabel(),wmNews);
                    break;
                case "review":
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "文章内容中有不确定因素，需要进一步人工审核:" ,wmNews);
                    break;
                case "pass":
                    flag=true;
                    break;
                default:
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用状态异常，需要进一步人工审核:" ,wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //人工审核
            updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "文章内容中有不确定因素，需要进一步人工审核:" ,wmNews);
        }
        return flag;
    }

    /**
     * 进行自动管理敏感词校验
     * @param content   待校验的文本
     * @param wmNews    文章对象
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        //feign远程查询敏感词列表
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        if(!sensitives.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败");
        }
        List<String> sensitivesData = sensitives.getData();
        //基于DFA算法，封装数据模型
        SensitiveWordUtil.initMap(sensitivesData);
        //基于DFA算法，检测是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(!CollectionUtils.isEmpty(map)){
            //如果包含，修改审核状态为2
            //wmNews.setStatus((short)2);
            //wmNews.setReason("文章中包含敏感词:"+map);
            //wmNewsMapper.updateById(wmNews);
            updateWmNews(WmNews.Status.FAIL.getCode(), "文章中包含敏感词: "+map ,wmNews);
            flag=false;
        }
        return flag;
    }

    /**
     * 修改审核状态
     * @param status    审核状态
     * @param reason    未通过原因
     * @param wmNews    文章对象
     */
    private void updateWmNews(Short status,String reason,WmNews wmNews){
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 抽取文章中所有文章内容和图片内容
     *
     * @param wmNews    文章对象
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        List<Map> mapList = JSON.parseArray(wmNews.getContent(), Map.class);
        //将文本内容拼接处字符串
        String content = mapList.stream()
                .filter(m -> "text".equals(m.get("type")))
                .map(m -> m.get("value").toString())
                .collect(Collectors.joining());
        //内容，标题合并
        content = wmNews.getTitle() + "_hmtt_" + content;
        //将图片路径存储在集合中
        List<String> images = mapList.stream()
                .filter(m -> "image".equals(m.get("type")))
                .map(m -> m.get("value").toString())
                .collect(Collectors.toList());
        //封面
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            List<String> coverImages = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            //合并
            images.addAll(coverImages);
        }
        //去重
        images = images.stream().distinct().collect(Collectors.toList());
        //将内容和路径封装成map集合
        Map<String, Object> result = new HashMap();
        result.put("content", content);
        result.put("images", images);
        return result;
    }
}
